﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThouShaltNotBrick.Models;
using System.Xml.Linq;
using System.IO;
using GMLogging;

namespace ThouShaltNotBrick.DataAccess
{
    public static class CampaignsXmlReader
    {
        #region Methods
        public static CampaignsData Read(string pCampaignsFilePath)
        {
            CampaignsData campaignsData = null;
            FileStream stream = null;
            try
            {
                stream = new FileStream(pCampaignsFilePath, FileMode.Open, FileAccess.Read);
                XDocument campaignsXDocument = XDocument.Load(stream);
                campaignsData = Parse(campaignsXDocument);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return campaignsData;
        }

        public static CampaignsData Parse(string pCampaignsInputString)
        {
            try
            {
                XDocument campaignsXDocument = XDocument.Parse(pCampaignsInputString);
                return Parse(campaignsXDocument);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                throw;
            }
        }

        private static CampaignsData Parse(XDocument pCampaignsXDocument)
        {
            XElement campaignsXElement = pCampaignsXDocument.Element(CampaignsXmlConstants.TAG_CAMPAIGNS);

            List<XElement> campaignXElements = campaignsXElement.Elements(CampaignsXmlConstants.TAG_CAMPAIGN).ToList();
            List<string> campaignList = new List<string>();
            foreach (XElement campaignXElement in campaignXElements)
            {
                XAttribute nameXAttribute = campaignXElement.Attribute(CampaignsXmlConstants.TAG_CAMPAIGN_ATTRIBUTE_NAME);

                string name = nameXAttribute.Value;
                campaignList.Add(name);
            }

            CampaignsData campaigns = new CampaignsData(campaignList);
            return campaigns;
        }
        #endregion
    }
}